package com.jingan.nursinghome.regulatory.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Camera;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Scroller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.android.support.v7.lib.sin.crown.base.BaseListenner;
import cn.android.support.v7.lib.sin.crown.utils.ProportionUtils;

/**
 * 滚轮选择器
 * Created by 彭治铭 on 2017/9/20.
 */

public class WheelTurns2 extends View implements View.OnTouchListener {
    public WheelTurns2(Context context) {
        super(context);
        init();
    }

    public WheelTurns2(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(width, height);
    }


    Map<Integer, Integer> mapIndex;//存储下标

    /**
     * 设置数据
     *
     * @param cScore 当前选中值。
     * @param values 数值数组，如 1,2,3或1900,1901等
     * @param unit   单位，如 年，月，日等
     */
    public void setData(int cScore, List<Integer> values, String unit, int width, int height, int count) {
        childViews.clear();
        for (int i = 0; i < values.size(); i++) {
            childViews.add(new ChildView(i, values.get(i), unit));
            mapIndex.put(values.get(i), i);
        }
        if (width > 0 || height > 0) {
            setMeasured(width, height, count);
        } else {
            invalidate();
        }

        int y = cScore * childHeight;
        if (getHeight() > 0) {
            y = y - getHeight() / 2 + childHeight / 2;
        } else {
            y = y - this.height / 2 + childHeight / 2;
        }
        //Log.e("test","y:\t"+y+"\t单个高:\t"+childHeight+"\t总高:\t"+getHeight()+"\tcScore:\t"+cScore);
        scrollTo(0, y);

    }

    public int getSize() {
        return childViews.size();
    }

    //更新
    public void upData(List<Integer> values, String unit) {
        childViews.clear();
        for (int i = 0; i < values.size(); i++) {
            childViews.add(new ChildView(i, values.get(i), unit));
            mapIndex.put(values.get(i), i);
        }
        invalidate();
    }

    List<ChildView> childViews;
    Paint paint;
    Scroller scroller;//滑動效果

    private void init() {
        mapIndex = new HashMap<>();
        //设置默认值
        childViews = new ArrayList<>();
//        for (int i = 0; i < 12; i++) {
//            childViews.add(new ChildView(i, i, "月"));
//        }
        scroller = new Scroller(getContext());
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setColor(textColor);
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        setOnTouchListener(this);
    }

    int width = (int) ProportionUtils.getInstance().realWidthPixels;
    int height = ProportionUtils.getInstance().adapterInt(400);//控件高度
    int centerY = height / 2;
    int count = 7;//列表显示行数,7和5效果应该最好。
    int childHeight = height / count;
    int textSize = (int) (childHeight * 0.6);//字体大小
    int textColor = Color.parseColor("#000000");//文本颜色

    //设置显示行数
    public void setCount(int count) {
        this.count = count;
    }

    //设置控件宽和高
    public void setMeasured(int width, int height, int count) {
        this.width = width;
        this.height = height;
        centerY = height / 2;
        this.count = count;//列表显示行数
        childHeight = height / this.count;
        textSize = (int) (childHeight * 0.6);//字体大小
        requestLayout();
    }

    //设置文本颜色
    public void setTextColor(int textColor) {
        this.textColor = textColor;
    }

    int startLine;
    int endLine;
    public int curentIndex;//当前选中下标
    public int curentValue;//当前选中值

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        canvas.drawColor(Color.parseColor("#D8E2EA"));
        startLine = centerY - childHeight / 2 + getScrollY();
        endLine = centerY + childHeight / 2 + getScrollY();
        int y = 0;

        int distance = getHeight();

        for (int i = 0; i < childViews.size(); i++) {
            childViews.get(i).updateBitamp(y);
            canvas.drawBitmap(childViews.get(i).getBitmap(), 0, y, paint);
            y += childViews.get(i).getBitmap().getHeight();

            //循环判断，找出离startLine最近的下标。
            int distance2 = Math.abs(childViews.get(i).y - startLine);
            if (distance2 < distance) {
                curentIndex = i;//自动检测当前选中下标
                curentValue = childViews.get(i).values;
                distance = distance2;
            }
        }
        maxScrollY = y - getHeight() / 2 - childHeight / 2;

        //渐变蒙版
        //new int[]{0xBBFAFAFA, 0x00FAFAFA, 0xBBFAFAFA}
//        linearGradient = new LinearGradient(0, getScrollY(), 0, getScrollY() + getHeight(), new int[]{0xBBFFFFFF, 0x00FFFFFF, 0xBBFFFFFF}, null, Shader.TileMode.CLAMP);
//        paint.setShader(linearGradient);
//        canvas.drawRect(new RectF(0, getScrollY(), getWidth(), getScrollY() + getHeight()), paint);
//        paint.setShader(null);

        //中间两条线
        canvas.drawLine(0, startLine, getWidth(), startLine, paint);
        canvas.drawLine(0, endLine, getWidth(), endLine, paint);

    }

    LinearGradient linearGradient;

    class ChildView {
        Paint paint;
        Camera camera;
        Matrix matrix;
        Bitmap bitmap;

        public int values;//数值
        public String unit;//单位，如 年，月，日等
        public int index;//下标
        public int y;//記錄y值坐標
        public int startLineDistance;//与startLine的距离(这个距离可以滑动到startLine)

        public ChildView(int index, int values, String unit) {
            this.index = index;
            this.values = values;
            this.unit = unit;
            paint = new Paint();
            camera = new Camera();
            matrix = new Matrix();
        }

        public Bitmap getBitmap() {
            return bitmap;
        }

        //刷新位图，获取位图之前，手动调用一次。
        //参数y画布上的位置
        public void updateBitamp(int y) {
            this.y = y;
            startLineDistance = y - (centerY - childHeight / 2);
            camera.save();

            paint.setColor(textColor);//颜色
            paint.setTextAlign(Paint.Align.CENTER);
            paint.setTextSize(textSize);//大小
            paint.setAntiAlias(true);
            paint.setDither(true);

            y += childHeight / 2;
            int centerscrollY = centerY + getScrollY();
            //分界线上部分
            if (y < centerscrollY) {
                int distanc = centerscrollY - y;//分界线的距离
                float bias = (float) distanc / (float) (centerY);//距离越大，比例越高
                bias = 1 - bias;
                camera.rotateX(90 * (1 - bias));//3D旋转效果
                paint.setTextSize(textSize / 5 * bias + textSize / 5 * 4);
            }
            //分界线下部分
            if (y > centerscrollY) {
                int distanc = y - centerscrollY;//分界线的距离
                float bias = (float) distanc / (float) (centerY);//距离越大，比例越高
                bias = 1 - bias;
                camera.rotateX(-90 * (1 - bias));//3D旋转效果
                paint.setTextSize(textSize / 5 * bias + textSize / 5 * 4);
            }

            if (bitmap == null || bitmap.isRecycled()) {
                bitmap = Bitmap.createBitmap(getWidth(), childHeight, Bitmap.Config.ALPHA_8);
            }

            Canvas canvas = new Canvas(bitmap);
            camera.getMatrix(matrix);
            matrix.preTranslate(-bitmap.getWidth() / 2, -bitmap.getHeight() / 2);
            matrix.postTranslate(bitmap.getWidth() / 2, bitmap.getHeight() / 2);
            canvas.concat(matrix);
            canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
            canvas.drawText(values + unit, bitmap.getWidth() / 2, (bitmap.getHeight()) / 2 + (int) (textSize * 0.8 / 2), paint);
            camera.restore();
        }
    }

    int maxScrollY;
    GestureDetector gestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            int y = (int) (getScrollY() + distanceY);
            if (y >= maxScrollY) {
                y = maxScrollY;
            }
            if (y <= -centerY + childHeight / 2) {
                y = -centerY + childHeight / 2;
            }
            WheelTurns2.this.scrollTo(0, y);
            return super.onScroll(e1, e2, distanceX, distanceY);
        }

    });


    //选中回调
    BaseListenner<Integer> baseListenner;

    public void setBaseListenner(BaseListenner<Integer> baseListenner) {
        this.baseListenner = baseListenner;
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        gestureDetector.onTouchEvent(motionEvent);
        if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
            //scrollTo(0, childViews.get(curentIndex).startLineDistance);
            if (childViews != null && childViews.size() > curentIndex) {
                smoothScrollBy(0, childViews.get(curentIndex).startLineDistance - getScrollY());
                if (baseListenner != null) {
                    baseListenner.onResult(childViews.get(curentIndex).values);
                }
            }
        }
        return true;
    }

    public void smoothScrollBy(int x, int y) {
        if (scroller != null && (x != getScrollX() || y != getScrollY())) {
            scroller.startScroll(getScrollX(), getScrollY(), x, y, 200);
            invalidate();
        }
    }

    //根據值，选中对于对象。必须等待activity或Dialog初始化完成之后调用才有效。所以初始化的时候最好延迟调用才有效。即invalidate()之后不能马上调用，要延迟几毫秒。
    public void selectVaules(int values, boolean smooth) {
        int index = mapIndex.get(values);
        if (childViews != null && childViews.size() > index) {
            if (smooth) {
                smoothScrollBy(0, childViews.get(index).startLineDistance - getScrollY());
            } else {
                scrollTo(0, childViews.get(index).startLineDistance);
            }
        }
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        if (scroller != null && scroller.computeScrollOffset()) {
            scrollTo(scroller.getCurrX(), scroller.getCurrY());
            postInvalidate();
        }
    }

}
